<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>待我审核</span>
      </div>
    </template>

    <!-- 批量操作按钮 -->
    <div style="margin-bottom: 10px">
      <el-button 
        type="success" 
        @click="handleBatchPass"
        :disabled="selectedIds.length === 0"
      >批量通过</el-button>
      <el-button 
        type="danger" 
        @click="handleBatchReject"
        :disabled="selectedIds.length === 0"
      >批量拒绝</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit"
        :disabled="selectedIds.length === 0"
      >批量提交</el-button>
      <span style="margin-left: 10px; color: #999;">已选择 {{ selectedIds.length }} 项</span>
    </div>

    <!-- 申请列表 -->
    <el-table 
      :data="applicationList" 
      style="width: 100%" 
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生姓名" prop="studentName" align="center" />
      <el-table-column label="学院" prop="college" align="center" />
      <el-table-column label="学年" align="center">
        <template #default="scope">
          {{ formatAcademicYear(scope.row.academicYear) }}
        </template>
      </el-table-column>
      <el-table-column label="困难等级" align="center">
        <template #default="scope">
          <el-tag :type="getDifficultyType(scope.row.difficultyLevel)">
            {{ formatDifficultyLevel(scope.row.difficultyLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核结果" align="center">
        <template #default="scope">
          <el-tag :type="getReviewResultType(scope.row)">
            {{ formatReviewResult(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
          <el-button 
            type="success" 
            size="small" 
            @click="handlePass(scope.row)"
            :disabled="!canReview(scope.row.status)"
          >通过</el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleReject(scope.row)"
            :disabled="!canReview(scope.row.status)"
          >拒绝</el-button>
          <el-button 
            type="warning" 
            size="small" 
            @click="handleSingleSubmit(scope.row)"
            :disabled="!canSubmit(scope.row)"
          >提交</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="queryParams.page"
      :page-size="queryParams.limit"
      :page-sizes="[10, 20, 30, 40]"
      :small="false"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @update:current-page="(val) => queryParams.page = val"
      @update:page-size="(val) => queryParams.limit = val"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="申请详情" width="600px">
      <el-form :model="currentApplication" label-width="120px">
        <el-form-item label="学生姓名">
          <el-input v-model="currentApplication.studentName" disabled />
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="currentApplication.college" disabled />
        </el-form-item>
        <el-form-item label="辅导员">
          <el-input v-model="currentApplication.counselor" disabled />
        </el-form-item>
        <el-form-item label="学年">
          <el-input :value="formatAcademicYear(currentApplication.academicYear)" disabled />
        </el-form-item>
        <el-form-item label="困难等级">
          <el-input :value="formatDifficultyLevel(currentApplication.difficultyLevel)" disabled />
        </el-form-item>
        <el-form-item label="审核阶段">
          <el-input :value="formatStatus(currentApplication.status)" disabled />
        </el-form-item>
        <el-form-item label="审核结果">
          <el-input :value="formatReviewResult(currentApplication)" disabled />
        </el-form-item>
        <el-form-item label="申请理由" v-if="currentApplication.applyReason">
          <el-input 
            v-model="currentApplication.applyReason" 
            type="textarea" 
            :rows="3" 
            disabled 
          />
        </el-form-item>
        <el-form-item label="拒绝理由" v-if="currentApplication.rejectedReason">
          <el-input 
            v-model="currentApplication.rejectedReason" 
            type="textarea" 
            :rows="3" 
            disabled 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 拒绝理由对话框 -->
    <el-dialog 
      v-model="rejectDialogVisible" 
      :title="isBatchReject ? `批量审核拒绝 (${currentRejectIds.length}项)` : '审核拒绝'" 
      width="500px"
    >
      <el-form :model="rejectForm" label-width="120px">
        <el-form-item label="拒绝理由">
          <el-input 
            v-model="rejectForm.rejectedReason" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入拒绝理由（非必填）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmReject">确认拒绝</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { _getMyApplication, _passApplication, _rejectApplication, _submitApplication } from '@/api/application'
import { ElMessage, ElMessageBox } from 'element-plus'

// 查询参数
const queryParams = ref({
  page: 1,
  limit: 10
})

// 申请列表
const applicationList = ref([])
const total = ref(0)
const loading = ref(false)

// 多选相关
const selectedIds = ref([])

// 当前操作的申请
const currentApplication = ref({})

// 详情对话框
const detailDialogVisible = ref(false)

// 拒绝对话框
const rejectDialogVisible = ref(false)
const rejectForm = ref({
  rejectedReason: ''
})
const currentRejectIds = ref([])  // 改为支持批量
const isBatchReject = ref(false)  // 标记是否批量拒绝

// 格式化学年
const formatAcademicYear = (year) => {
  if (!year) return '-'
  return `${year}-${year + 1}`
}

// 格式化困难等级
const formatDifficultyLevel = (level) => {
  const map = {
    1: '一般困难',
    2: '困难',
    3: '特别困难'
  }
  return map[level] || '-'
}

// 获取困难等级标签类型
const getDifficultyType = (level) => {
  const map = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return map[level] || 'info'
}

// 格式化审核阶段（原status）
const formatStatus = (status) => {
  const map = {
    0: '已拒绝',
    1: '辅导员审核中',
    2: '学院审核中',
    3: '学校审核中',
    4: '已通过'
  }
  return map[status] || '-'
}

// 格式化审核结果（根据status显示对应的审核结果）
const formatReviewResult = (row) => {
  const { status, counselorResult, collegeResult, schoolResult } = row
  
  // 根据审核阶段显示对应的审核结果
  if (status === 1) {
    // 辅导员审核阶段
    if (counselorResult === 1) return '通过'
    if (counselorResult === 2) return '拒绝'
    return '待审核'
  } else if (status === 2) {
    // 学院审核阶段
    if (collegeResult === 1) return '通过'
    if (collegeResult === 2) return '拒绝'
    return '待审核'
  } else if (status === 3) {
    // 学校审核阶段
    if (schoolResult === 1) return '通过'
    if (schoolResult === 2) return '拒绝'
    return '待审核'
  } else if (status === 0) {
    return '已拒绝'
  } else if (status === 4) {
    return '已通过'
  }
  return '-'
}

// 获取审核结果标签类型
const getReviewResultType = (row) => {
  const { status, counselorResult, collegeResult, schoolResult } = row
  
  // 根据审核阶段获取对应的审核结果
  let result = null
  if (status === 1) result = counselorResult
  else if (status === 2) result = collegeResult
  else if (status === 3) result = schoolResult
  else if (status === 0) return 'danger'  // 已拒绝
  else if (status === 4) return 'success' // 已通过
  
  // 根据审核结果返回标签类型
  if (result === 1) return 'success'  // 通过-绿色
  if (result === 2) return 'danger'   // 拒绝-红色
  return 'warning'  // 待审核-橙色
}

// 判断是否可以审核（状态为1/2/3时可以审核，0和4不能审核）
const canReview = (status) => {
  return status === 1 || status === 2 || status === 3
}

// 判断是否可以提交（已审核通过或拒绝的可以提交）
const canSubmit = (row) => {
  const { status, counselorResult, collegeResult, schoolResult } = row
  
  // 根据审核阶段判断是否已审核
  if (status === 1) {
    // 辅导员审核阶段，已有审核结果才能提交
    return counselorResult === 1 || counselorResult === 2
  } else if (status === 2) {
    // 学院审核阶段，已有审核结果才能提交
    return collegeResult === 1 || collegeResult === 2
  } else if (status === 3) {
    // 学校审核阶段，已有审核结果才能提交
    return schoolResult === 1 || schoolResult === 2
  }
  return false
}

// 获取申请列表
const getApplicationList = () => {
  loading.value = true
  _getMyApplication(queryParams.value).then(res => {
    if (res.code === 200) {
      applicationList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  }).catch(err => {
    console.error('获取申请列表失败:', err)
    ElMessage.error('获取申请列表失败')
  }).finally(() => {
    loading.value = false
  })
}

// 处理表格多选
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 查看详情
const handleDetail = (row) => {
  // 直接使用列表数据，避免后端Application实体缺少展示字段
  currentApplication.value = { ...row }
  detailDialogVisible.value = true
}

// 审核通过（单个）
const handlePass = (row) => {
  ElMessageBox.confirm('确认通过该申请吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const params = {
      ids: [row.id]
    }
    _passApplication(params).then(res => {
      if (res.code === 200) {
        ElMessage.success('审核通过成功')
        getApplicationList()
      }
    }).catch(err => {
      console.error('审核通过失败:', err)
      ElMessage.error('审核通过失败')
    })
  }).catch(() => {
    // 取消操作
  })
}

// 批量通过
const handleBatchPass = () => {
  ElMessageBox.confirm(`确认通过选中的 ${selectedIds.value.length} 个申请吗？`, '批量审核通过', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const params = {
      ids: selectedIds.value
    }
    _passApplication(params).then(res => {
      if (res.code === 200) {
        ElMessage.success('批量审核通过成功')
        selectedIds.value = []
        getApplicationList()
      }
    }).catch(err => {
      console.error('批量审核通过失败:', err)
      ElMessage.error('批量审核通过失败')
    })
  }).catch(() => {
    // 取消操作
  })
}

// 打开拒绝对话框（单个）
const handleReject = (row) => {
  currentRejectIds.value = [row.id]
  isBatchReject.value = false
  rejectForm.value.rejectedReason = ''
  rejectDialogVisible.value = true
}

// 批量拒绝
const handleBatchReject = () => {
  currentRejectIds.value = [...selectedIds.value]
  isBatchReject.value = true
  rejectForm.value.rejectedReason = ''
  rejectDialogVisible.value = true
}

// 确认拒绝
const confirmReject = () => {
  const params = {
    ids: currentRejectIds.value,
    rejectedReason: rejectForm.value.rejectedReason || ''
  }
  _rejectApplication(params).then(res => {
    if (res.code === 200) {
      ElMessage.success(isBatchReject.value ? '批量审核拒绝成功' : '审核拒绝成功')
      rejectDialogVisible.value = false
      if (isBatchReject.value) {
        selectedIds.value = []
      }
      getApplicationList()
    }
  }).catch(err => {
    console.error('审核拒绝失败:', err)
    ElMessage.error('审核拒绝失败')
  })
}

// 单个提交
const handleSingleSubmit = (row) => {
  ElMessageBox.confirm(
    `确认提交该申请吗？提交后申请将进入下一审核阶段。`,
    '提交审核',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    _submitApplication([row.id]).then(res => {
      if (res.code === 200) {
        ElMessage.success('提交成功')
        getApplicationList()
      }
    }).catch(err => {
      console.error('提交失败:', err)
      ElMessage.error('提交失败')
    })
  }).catch(() => {
    // 取消操作
  })
}

// 批量提交
const handleSubmit = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要提交的申请')
    return
  }
  
  ElMessageBox.confirm(
    `确认提交选中的 ${selectedIds.value.length} 个申请吗？提交后申请将进入下一审核阶段。`,
    '批量提交审核',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    _submitApplication(selectedIds.value).then(res => {
      if (res.code === 200) {
        ElMessage.success('批量提交成功')
        selectedIds.value = []
        getApplicationList()
      }
    }).catch(err => {
      console.error('提交失败:', err)
      ElMessage.error('提交失败')
    })
  }).catch(() => {
    // 取消操作
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.limit = val
  queryParams.value.page = 1
  getApplicationList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  queryParams.value.page = val
  getApplicationList()
}

// 页面加载时获取数据
onMounted(() => {
  getApplicationList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

